const mongoose = require('mongoose');
const validator = require('validator');
const videoSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: [true, 'Please tell  us video name'],
    },
    url: {
      type: String,
      required: [true, 'Please provide video url'],
    },
    description: String,
    //review --》 video
    footer: {
      type: String,
      default: 'http://127.0.0.1:3000/upload/视频封面mobile-01-p3g.png',
    },
    createAt: {
      type: Date,
      default: Date.now(),
    },

    //means the 播放次数
    playCount: {
      type: Number,
      default: 0,
    },
    active: {
      type: Boolean,
      default: true,
      select: false,
    },
    user: {
      type: mongoose.Schema.ObjectId,
      ref: 'User',
      required: [true, 'Video must belong to a user'],
    },
    //  引用收藏夹
    favoriteNames: [
      {
        type: mongoose.Schema.ObjectId,
        ref: 'FavoriteName',
        default: [],
      },
    ],
    // 引用 评论数组
    videoReviews: [
      {
        type: mongoose.Schema.ObjectId,
        ref: 'VideoReview',
      },
    ],
    danmus: [
      {
        type: mongoose.Schema.ObjectId,
        ref: 'Danmu',
      },
    ],
  },
  {
    toJSON: { virtuals: true },
    toObject: { virtuals: true },
  }
);

// 添加虚拟属性来计算 favoriteNames 数组的长度
videoSchema.virtual('favoriteNamesCount').get(function () {
  if (this.favoriteNames) {
    return this.favoriteNames.length;
  }
});

// 在查询时排除 favoriteNames 字段，只显示其长度
// videoSchema.pre(/^find/, function (next) {
//   this.select('-favoriteNames');
//   next();
// });

videoSchema.pre(/^find/, function (next) {
  this.populate({
    path: 'videoReviews',
    select: 'review createAt rating',
  });
  this.populate({
    path: 'danmus',
    select: 'txt start',
  });
  this.populate({
    path: 'user',
    select: 'name  photo',
  });
  next();
});
videoSchema.pre(/^find/, function (next) {
  this.find({ active: { $ne: false } });
  next();
});

const Video = mongoose.model('Video', videoSchema);

module.exports = Video;
